package com.study.webapp.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockInterrupt implements Runnable {
	private static ReentrantLock lock = new ReentrantLock();

	@Override
	public void run() {
		try {
			// 申请锁，这是可以进中断申请的申请锁操作
			lock.lockInterruptibly();
			// 睡眠20秒，在结束之前，main方法中要中断t2的获取锁操作
			Thread.sleep(20000);
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			String threadName = Thread.currentThread().getName();
			// 中断后跑出异常，最后释放锁
			// 如果t1就释放，因为t2没有拿到锁，所以不用释放
			if ("Tread-1".equals(threadName)) {
				lock.unlock();
			}
			System.out.println(threadName + "：停止");

		}
	}

	public static void main(String[] args) {
		ReentrantLockInterrupt in = new ReentrantLockInterrupt();
		Thread t1 = new Thread(in, "Thread-1");
		Thread t2 = new Thread(in, "Thread-2");
		t1.start();
		try {
			// 让主线程停一下，先让t1获得锁再启动t2
			Thread.sleep(1000);
		} catch (Exception e) {
			// TODO: handle exception
		}
		t2.start();
		t2.interrupt();
		/**
		 * 过程是t1拿到锁然后睡眠20秒，然后开始t2线程，t2线程没有拿到锁就可以直接中断停止，然后t1醒来，释放锁
		 */
	}

}
